package cn.huapu.power.energy.util.token;

import cn.huapu.power.energy.ex.ErrorCodesException;
import cn.huapu.power.energy.util.AesEncryptUtils;
import cn.huapu.power.energy.util.Configurationn;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * https://blog.csdn.net/weixin_41835866/article/details/82119017  demo地址
 */
@Configuration
public class JwtUtil {

    //私钥
    static String base64EncodedSecretKey = "";


    static {
        try {
            base64EncodedSecretKey = AesEncryptUtils.decrypt((String) Configurationn.getConfigsetting().getProperty("tokenSy"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //过期时间为7天
    final static long TOKEN_EXP = 1000 * 60 * 10080;


    public static String getToken(String userName, String userId, String clientId) {

        return Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("userName", userName).claim("userId", userId).claim("clientId", clientId)
                /*过期时间*/
                .setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXP))
                .signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey).compact();

    }


    public static Claims checkToken(String token) {

        try {

            final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();

            return claims;

        } catch (ExpiredJwtException e1) {

            throw new ErrorCodesException("登录信息过期，请重新登录", ErrorCodesException.LOGIN_ERR);

        } catch (Exception e) {

            throw new ErrorCodesException("token错误", ErrorCodesException.LOGIN_ERR);

        }


    }

}
